#include "chataudio.h"
#include <QtCore/QDebug>

ChatAudio::ChatAudio(QObject *parent) : QObject(parent)
{
    initialize(QAudioDeviceInfo::defaultInputDevice());
}

void ChatAudio::initialize(const QAudioDeviceInfo &deviceInfo)
{
    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setSampleType(QAudioFormat::SignedInt);
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setCodec("audio/pcm");

    if (!deviceInfo.isFormatSupported(format)) {
        qWarning() << "Default format not supported - trying to use nearest";
        format = deviceInfo.nearestFormat(format);
    }

    m_audioInfo.reset(new AudioInfo(format));

    m_audioInput.reset(new QAudioInput(deviceInfo, format));
    connect(m_audioInput.data(),&QAudioInput::stateChanged,this,&ChatAudio::inputStateChanged);

    m_audioOutput.reset(new QAudioOutput(deviceInfo,format));
    connect(m_audioOutput.data(),&QAudioOutput::stateChanged,this,&ChatAudio::outputStateChanged);
}

void ChatAudio::inputToggleMode()
{
    if (m_audioInput->state() == QAudio::SuspendedState || m_audioInput->state() == QAudio::StoppedState) {//中断或停止状态
        m_audioInput->resume();//继续
        auto io = m_audioInput->start();
        if(io != nullptr){
            connect(io, &QIODevice::readyRead,
                    [&, io]() {
                qint64 len = m_audioInput->bytesReady();
                const int BufferSize = 4096;
                if (len > BufferSize)
                    len = BufferSize;

                QByteArray buffer(len, 0);
                qint64 l = io->read(buffer.data(), len);
                if (l > 0)
                    m_data.append(buffer);
                    //m_data.resize(m_data.size()+l);
                    //m_data.fill(buffer);
                    //m_audioInfo->write(buffer.constData(), l);
            });
        }
    } else if (m_audioInput->state() == QAudio::ActiveState) {//激活状态
        m_audioInput->suspend();//中断
    } else if (m_audioInput->state() == QAudio::IdleState) {//空闲状态
        // no-op
    }
}

void ChatAudio::outputToggleMode(QString message)
{
    QByteArray data = message.toLatin1();
    m_audioInfo->start();
    m_audioInfo->write(data);
    m_audioOutput->start(m_audioInfo.data());
}

QByteArray ChatAudio::getData(){
    return m_data;

}

void ChatAudio::clearData(){
    m_data.clear();
}
